import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-06-16
 * Time: 9:53
 */

class Solution6 {
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;
    public List<List<Integer>> permuteUnique(int[] nums) {
        //先排序
        Arrays.sort(nums);
        ret = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];

        dfs(nums,0);

        return ret;
    }

    void dfs(int[] nums, int pos) {
        if(pos == nums.length) {
            ret.add(new ArrayList<>(path));
            return;
        }

        for(int i = 0; i < nums.length; i++) {
            if(check[i] == true || (i != 0 && nums[i] == nums[i-1] && check[i-1] == false)) {
                continue;
            }
            path.add(nums[i]);
            check[i] = true;
            dfs(nums,pos+1);
            //回溯 恢复现场
            path.remove(path.size()-1);
            check[i] = false;
        }
    }
}